package tripx.sql;

import java.lang.reflect.Field;

public abstract class QueryObject {

	/**
	 * get all the field names, except the private fields
	 * 
	 * @return a string array contains the field names
	 */
	public String[] getFields() {
		Field[] fields = getClass().getFields();
		String[] values = new String[fields.length];
		for (int i = 0; i < values.length; i++) {
			values[i] = fields[i].getName();
		}
		return values;
	}

	/**
	 * get the specified field value
	 * 
	 * @param fieldName
	 * @return return the field value, if error happened, an empty string will
	 *         returned
	 */
	public String getFieldValue(String fieldName, String defaultValue) {
		try {
			Field field = getClass().getDeclaredField(fieldName);
			Object obj = field.get(this);
			if (obj == null) {
				return defaultValue;
			}
			return field.get(this).toString();
		} catch (IllegalArgumentException | IllegalAccessException
				| NoSuchFieldException | SecurityException e) {
			return defaultValue;
		}
	}

	/**
	 * get the field class type
	 * 
	 * @param fieldName
	 * @return the simple class name with string format
	 */
	public String getFieldClass(String fieldName) {
		try {
			Field field = getClass().getDeclaredField(fieldName);
			return field.getType().getSimpleName();
		} catch (NoSuchFieldException | SecurityException e) {
			return null;
		}
	}
}
